package jmine.tec.utils.spring.http;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import jmine.tec.utils.spring.InstanceResolver;

/**
 * Instance resolver that bounds instances to {@link Thread}s.
 * 
 * @author takeshi
 * @param <E> type
 */
public class ThreadBoundInstaceResolver<E> extends AbstractInstanceResolver<E> implements InstanceResolver<E>, Externalizable {

    private static final long serialVersionUID = 444052067162899942L;

    private final ThreadLocal<E> instances = new ThreadLocal<E>();

    /**
     * 
     * 
     */
    public ThreadBoundInstaceResolver() {
    }

    /**
     * @return {@link Object}
     */
    @Override
    public final E resolveInstance() {
        E instance = this.instances.get();
        if (instance == null) {
            instance = this.findInstance();
            this.setInstance(instance);
        }
        return instance;
    }

    /**
     * @param object {@link Object}
     */
    public final void setInstance(final E object) {
        this.instances.set(object);
    }

    /**
     * 
     * 
     */
    public final void clearCurrentInstance() {
        this.instances.remove();
    }

    /**
     * 
     * 
     */
    public final void clear() {
        this.instances.remove();
    }

    /**
     * @param in {@link ObjectInput}
     * @throws IOException e
     * @throws ClassNotFoundException e
     */
    public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
    }

    /**
     * @param out {@link ObjectOutput}
     * @throws IOException e
     */
    public void writeExternal(final ObjectOutput out) throws IOException {
    }

    /**
     * Hook for subclasses to find instances.
     * 
     * @return E
     */
    protected E findInstance() {
        return null;
    }
}
